package cn.uexpo.lhz.controller.admin;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.uexpo.lhz.common.oldUtils.PageRequest;
import cn.uexpo.lhz.common.oldUtils.PageResult;
import cn.uexpo.lhz.core.http.HttpResult;
import cn.uexpo.lhz.domain.ManageEquipmentVo;
import cn.uexpo.lhz.plus.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.uexpo.lhz.biz.ManageEquipmentBiz;
import cn.uexpo.lhz.common.MqttGateway;
import cn.uexpo.lhz.common.oldBase.BaseController;
import cn.uexpo.lhz.common.utils.JsonData;
import cn.uexpo.lhz.common.utils.StringUtil;
import cn.uexpo.lhz.domain.ManageEquipment;
import cn.uexpo.lhz.domain.ManageEquipmentExample;

/**
 * 设备管理
 *
 * @author
 * @since
 */
@RestController
@RequestMapping("/cert/equipment")
public class ManageEquipmentController extends BaseController<ManageEquipment> {

    @Autowired
    private ManageEquipmentBiz manageEquipmentBiz;

    @Autowired
    private MqttGateway mqttGateway;//等于网关的作用



    /**
     * 批量停用设备
     * @param list
     * @return
     */
    @PostMapping("/updateByextStr2s")
    public Object updateByextStr2s(@RequestBody List<Integer> list){
        manageEquipmentBiz.updateByextStr2s(list);
        return JsonData.toJsonMessage("批量停用设备成功", "0", true);
    }


    /**
     * 解除设备位置
     *
     * @param equipment
     * @return
     */
    @RequestMapping("/relieveEquipmentLocation")
    @ResponseBody
    public Object relieveEquipmentLocation(@RequestBody ManageEquipment equipment) {
        manageEquipmentBiz.updateByPrimaryKey2(equipment);
        return JsonData.toJsonObject("解除设备位置成功", "200", true, equipment);
    }

//    @RequestMapping("/relieveEquipmentLocation")
//    @ResponseBody
//    public Object relieveEquipmentLocation(@RequestBody ManageEquipment equipment) {
//    	ManageEquipmentExample example=new ManageEquipmentExample();
//    	ManageEquipmentExample.Criteria criteria=example.createCriteria();
//    	if(equipment.getId()!=null) {
//    		criteria.andIdEqualTo(equipment.getId());//根据设备ID进行解除
//    	}
//    	manageEquipmentBiz.updateByExampleSelective(equipment, example);
//    	return JsonData.toJsonObject("解除设备位置成功", "200", true,equipment);
//    }


    /**
     * 查询一个设备下的位置,活动,项目
     *
     * @param equipment
     * @return
     */
    @RequestMapping("/findManageEquipmentDependencyAll")
    @ResponseBody
    public Object findManageEquipmentDependencyAll(@RequestBody ManageEquipment equipment) {
        List<ManageEquipment> list = manageEquipmentBiz.selectManageEquipmentDependencyAllByID(equipment);
        Map<String, Object> map = new HashMap<>();
        map.put("msg", 200);
        map.put("data", list);
        //map转成json数据
        JSONArray jArray = new JSONArray();
        jArray.add(map);
        String data = jArray.toString();
        //把传递数据放入mq当中(主题方式)
        mqttGateway.sendToMqtt(data, "EventDependencyMsg");//发送EventDependencyMsg主题
        return data;
    }

    /**
     * 为项目的相关位置添加设备
     *
     * @param equipment
     * @return
     */
    @PostMapping("/addEventLocationEquipmentSingle")
    public R addEventLocationEquipmentSingle(@RequestBody ManageEquipment equipment) {
        ManageEquipmentExample example = new ManageEquipmentExample();
        ManageEquipmentExample.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotBlank(equipment.getName())) {
            criteria.andNameEqualTo(equipment.getName());
        }
        int result = manageEquipmentBiz.updateByExampleSelective(equipment, example);
        if (result > 0) {
            JSONArray jArray1 = new JSONArray();
            JSONArray jArray2 = new JSONArray();

            Map<String, Object> map1 = new HashMap<>();
            Map<String, Object> map = new HashMap<>();
            map1.put("msg", 200);
            map1.put("data", jArray2);

            map.put("locationName", equipment.getLocation());
            map.put("activityName", equipment.getActivity());
            map.put("eventName", equipment.getItem());
            map.put("equipmentName", equipment.getName());

            jArray1.add(map1);
            jArray2.add(map);

            String EventDependencyMsg = jArray1.toString();
            //把传递数据放入mq当中(主题方式)
            mqttGateway.sendToMqtt(EventDependencyMsg, "EventDependencyMsg");//发送EventDependencyMsg主题
        }
        return R.ok("已添加该设备");
    }

    /**
     * 查询所有设备
     *
     * @param
     * @return
     */
    //查询项目设备表中位置,活动,项目,位置ID为null的设备信息
    @GetMapping("/findEquipmentAll2")
    public R findEquipmentAll2() {
        ManageEquipment equipment = new ManageEquipment();
        List<Map> list = manageEquipmentBiz.selectManageEquipmentAll(equipment);
        return R.ok().put("list", list);
    }

    //查询项目设备中的所有信息
    @RequestMapping("/findEquipmentAll")
    @ResponseBody
    public Object findEquipmentAll(ManageEquipment equipment) {
        ManageEquipmentExample example = new ManageEquipmentExample();
        List<ManageEquipment> list = manageEquipmentBiz.selectByExample(example);
        JsonData jsonData = new JsonData();
        jsonData.setCode(200);
        jsonData.setData(list);
        return jsonData;
    }

    /**
     * 根据项目位置ID查询对应设备
     *
     * @param
     * @return
     */
    @GetMapping("/findEventLocationEquipmentAll")
    public R findEventLocationEquipmentAll(@RequestParam("extstr1") String extstr1) {
        ManageEquipmentExample example = new ManageEquipmentExample();
        ManageEquipmentExample.Criteria criteria = example.createCriteria();
        int parseInt = Integer.parseInt(extstr1);
        if (parseInt != 0) {
            criteria.andExtstr1EqualTo(parseInt);
        }
        example.setOrderByClause("id desc");
        List<ManageEquipment> list = manageEquipmentBiz.selectByExample(example);
        return R.ok().put("list", list);
    }


    /**
     * 根据设备ID查询设备
     *
     * @param equipment
     * @return
     */
    @RequestMapping("/findEquipmentAllBYId")
    @ResponseBody
    public Object findEquipmentAllBYId(ManageEquipment equipment) {
        return JsonData.toJsonObject("查询成功", "200", true, manageEquipmentBiz.selectByPrimaryKey(equipment.getId()));
    }


    /**
     * 设备信息录入     人脸识别设备注册
     *
     * @return
     * @throws Exception
     */
    @SuppressWarnings("restriction")
    @RequestMapping(value = "/equipmentData", method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> data(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String code = "500";
        String msg = "失败";
        Map<String, Object> map = new HashMap<String, Object>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String name = request.getParameter("name");//设备名称
        String deviceIp = request.getParameter("deviceIp");//设备ip
        String deviceId = request.getParameter("deviceId");//设备id
        String type = request.getParameter("type");//设备类型
        String model = request.getParameter("model");//设备型号
//        String location = request.getParameter("location");//设备位置   设备地址不需要传
        String version = request.getParameter("version");//设备版本
        String lastOnlineTime = request.getParameter("lastOnlineTime");//最后在线时间
        String state = request.getParameter("state");//状态
        String stateInstruction = request.getParameter("stateInstruction");//状态说明
        if (null != name && !"".equals(name) && null != deviceId && !"".equals(deviceId)) {
            ManageEquipmentExample example = new ManageEquipmentExample();
            ManageEquipmentExample.Criteria citeria = example.createCriteria();
//             citeria.andNameEqualTo(name);
            citeria.andDeviceidEqualTo(deviceId);//具有唯一性
            List<ManageEquipment> equipments = manageEquipmentBiz.selectByExample(example);
            int no = 0;
            if (null != equipments && equipments.size() > 0) {
                ManageEquipment manageEquipment = equipments.get(0);
                manageEquipment.setName(name);
                manageEquipment.setDeviceip(deviceIp);
//                 manageEquipment.setDeviceid(deviceId);
//                 manageEquipment.setType(type);
//                 manageEquipment.setModel(model);
//                 manageEquipment.setLocation(location);
                manageEquipment.setVersion(version);
                manageEquipment.setLastonlinetime(sdf.parse(lastOnlineTime));
                manageEquipment.setState(state);
                manageEquipment.setStateinstruction(stateInstruction);

                no = manageEquipmentBiz.updateByPrimaryKeySelective(manageEquipment);
            } else {
                ManageEquipment manageEquipment = new ManageEquipment();
                manageEquipment.setName(name);
                manageEquipment.setDeviceip(deviceIp);
                manageEquipment.setDeviceid(deviceId);
                manageEquipment.setType(type);
                manageEquipment.setModel(model);
//                 manageEquipment.setLocation(location);
                manageEquipment.setVersion(version);
                manageEquipment.setLastonlinetime(sdf.parse(lastOnlineTime));
                manageEquipment.setState(state);
                manageEquipment.setStateinstruction(stateInstruction);
                //第一次注册是否停用状态默认可用
                manageEquipment.setExtstr2("1");
                //第一次注册是否进行身份证1比1比较默认比较
                manageEquipment.setExtstr5("0");
                no = manageEquipmentBiz.insert(manageEquipment);
            }
            if (1 == no) {
                code = "200";
                msg = "成功";
            }
        } else {
            code = "500";
            msg = "设备名称或设备ID不能为空";
        }


        map.put("code", code);
        map.put("msg", msg);
        return map;
    }


//	/**
//	 * 设备信息录入     人脸识别设备注册
//	 * @return
//	 * @throws Exception
//	 */
//	@SuppressWarnings("restriction")
//	@RequestMapping(value = "/equipmentData", method = { RequestMethod.POST })
//	@ResponseBody
//	public Map<String, Object> data (HttpServletRequest request,HttpServletResponse response) throws Exception {
//		String code = "500";
//		String msg = "失败";
//		Map<String, Object> map = new HashMap<String, Object>();
//		SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		String name = request.getParameter("name");//设备名称
//		String deviceIp = request.getParameter("deviceIp");//设备ip
//		String deviceId = request.getParameter("deviceId");//设备id
//		String type = request.getParameter("type");//设备类型
//		String model = request.getParameter("model");//设备型号
////        String location = request.getParameter("location");//设备位置   设备地址不需要传
//		String version = request.getParameter("version");//设备版本
//		String lastOnlineTime = request.getParameter("lastOnlineTime");//最后在线时间
//		String state = request.getParameter("state");//状态
//		String stateInstruction = request.getParameter("stateInstruction");//状态说明
//		if(null!=name&&!"".equals(name)&&null!=deviceId&&!"".equals(deviceId)) {
//			ManageEquipmentExample example = new ManageEquipmentExample();
//			ManageEquipmentExample.Criteria citeria = example.createCriteria();
////             citeria.andNameEqualTo(name);
//			citeria.andDeviceidEqualTo(deviceId);//具有唯一性
//			List<ManageEquipment> equipments = manageEquipmentBiz.selectByExample(example);
//			int no = 0;
//			if(null!=equipments&&equipments.size()>0){
//				ManageEquipment manageEquipment = equipments.get(0);
//				manageEquipment.setName(name);
//				manageEquipment.setDeviceip(deviceIp);
////                 manageEquipment.setDeviceid(deviceId);
////                 manageEquipment.setType(type);
////                 manageEquipment.setModel(model);
////                 manageEquipment.setLocation(location);
//				manageEquipment.setVersion(version);
//				manageEquipment.setLastonlinetime(sdf.parse(lastOnlineTime));
//				manageEquipment.setState(state);
//				manageEquipment.setStateinstruction(stateInstruction);
//				no = manageEquipmentBiz.updateByPrimaryKeySelective(manageEquipment);
//			}else{
//				ManageEquipment manageEquipment = new ManageEquipment();
//				manageEquipment.setName(name);
//				manageEquipment.setDeviceip(deviceIp);
//				manageEquipment.setDeviceid(deviceId);
//				manageEquipment.setType(type);
//				manageEquipment.setModel(model);
////                 manageEquipment.setLocation(location);
//				manageEquipment.setVersion(version);
//				manageEquipment.setLastonlinetime(sdf.parse(lastOnlineTime));
//				manageEquipment.setState(state);
//				manageEquipment.setStateinstruction(stateInstruction);
//				//第一次注册是否停用状态默认可用
//				manageEquipment.setExtstr2("1");
//				no = manageEquipmentBiz.insert(manageEquipment);
//			}
//			if(1==no){
//				code = "200";
//				msg = "成功";
//			}
//		}else {
//			code = "500";
//			msg = "设备名称或设备ID不能为空";
//		}
//
//
//		map.put("code", code);
//		map.put("msg", msg);
//		return map;
//	}


    @PostMapping(value = "/state")
    @ResponseBody
    public R state(@RequestBody ManageEquipment manageEquipment) {
        Map<String, Object> map = new HashMap<String, Object>();
        int no = 0;
        String code = "500";
        String msg = "失败";

        int id = manageEquipment.getId();
        String name = manageEquipment.getName();
        String state = manageEquipment.getExtstr2();
        String deviceId = manageEquipment.getDeviceid();
        ManageEquipmentExample example = new ManageEquipmentExample();
        ManageEquipmentExample.Criteria citeria = example.createCriteria();
        citeria.andIdEqualTo(id);
        citeria.andNameEqualTo(name);
        List<ManageEquipment> equipments = manageEquipmentBiz.selectByExample(example);
        if (equipments.size() > 0 && null != equipments) {
            ManageEquipment equipment = equipments.get(0);
            equipment.setExtstr2(state);
            no = manageEquipmentBiz.updateByPrimaryKeySelective(equipment);
        }
        if (1 == no) {
            code = "200";
            msg = "成功";
        }
        map.put("code", code);
        map.put("msg", msg);
        map.put("name", name);
        map.put("state", state);
        map.put("deviceId", deviceId);
        //map转成json数据
        JSONObject jObject = new JSONObject();
        jObject.put("code", code);
        jObject.put("msg", msg);
        jObject.put("name", name);
        jObject.put("state", state);
        jObject.put("deviceId", deviceId);
        String data = jObject.toString();
        mqttGateway.sendToMqtt(data, "equipmentState");//发送equipmentState主题
        return R.ok(map);
    }


    @PostMapping(value = "/idcComparison")
    @ResponseBody
    public Map<String, Object> idcComparison(@RequestBody ManageEquipment manageEquipment) {
        Map<String, Object> map = new HashMap<String, Object>();
        int no = 0;
        String code = "500";
        String msg = "失败";

        int id = manageEquipment.getId();
        String name = manageEquipment.getName();
        String idcComparison = manageEquipment.getExtstr5();
        String deviceId = manageEquipment.getDeviceid();
        String item = manageEquipment.getItem();
        ManageEquipmentExample example = new ManageEquipmentExample();
        ManageEquipmentExample.Criteria citeria = example.createCriteria();
        citeria.andIdEqualTo(id);
        citeria.andNameEqualTo(name);
        if (item != null && "".equals(item)) {
            citeria.andItemEqualTo(item);
        }
        List<ManageEquipment> equipments = manageEquipmentBiz.selectByExample(example);
        if (equipments.size() > 0 && null != equipments) {
            ManageEquipment equipment = equipments.get(0);
            equipment.setExtstr5(idcComparison);
            no = manageEquipmentBiz.updateByPrimaryKeySelective(equipment);
        }
        if (1 == no) {
            code = "200";
            msg = "成功";
        }
        map.put("code", code);
        map.put("msg", msg);
        map.put("name", name);
        map.put("idcComparison", idcComparison);
        map.put("deviceId", deviceId);
        map.put("item", item);
        //map转成json数据
        JSONObject jObject = new JSONObject();
        jObject.put("code", code);
        jObject.put("msg", msg);
        jObject.put("name", name);
        jObject.put("idcComparison", idcComparison);
        jObject.put("deviceId", deviceId);
        jObject.put("item", item);
        String data = jObject.toString();
        mqttGateway.sendToMqtt(data, "idcComparison");//发送equipmentState主题
        return map;
    }


    /**
     * 修改名字
     *
     * @param manageEquipment
     * @return
     */
    @PostMapping(value = "/edit")
    @ResponseBody
    public Map<String, Object> edit(@RequestBody ManageEquipment manageEquipment) {
        Map<String, Object> map = new HashMap<String, Object>();
        int no = 0;
        String code = "500";
        String msg = "失败";
        int id = manageEquipment.getId();
        String name = manageEquipment.getName();
        String deviceId = manageEquipment.getDeviceid();
        ManageEquipmentExample example = new ManageEquipmentExample();
        ManageEquipmentExample.Criteria citeria = example.createCriteria();
        citeria.andIdEqualTo(id);
        List<ManageEquipment> equipments = manageEquipmentBiz.selectByExample(example);

        if (null != name && !"".equals(name)) {
            ManageEquipmentExample example1 = new ManageEquipmentExample();
            ManageEquipmentExample.Criteria citeria1 = example1.createCriteria();
            citeria1.andNameEqualTo(name);
            List<ManageEquipment> equipments1 = manageEquipmentBiz.selectByExample(example1);

            if (equipments1.size() > 0 && null != equipments1) {
                msg = "名字已经存在";
            } else if (equipments.size() > 0 && null != equipments) {
                ManageEquipment equipment = equipments.get(0);
                equipment.setName(name);
                no = manageEquipmentBiz.updateByPrimaryKeySelective(equipment);
            }
        } else {
            msg = "名字不能为空";
        }
        if (1 == no) {
            code = "200";
            msg = "成功";
            JSONObject jObject = new JSONObject();
            jObject.put("code", code);
            jObject.put("msg", msg);
            jObject.put("name", name);
            jObject.put("deviceId", deviceId);
            String data = jObject.toString();
            mqttGateway.sendToMqtt(data, "equipmentEdit");//发送equipmentEdit主题
        }
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }


    //  @PreAuthorize("hasAuthority('biz:equipment:view')")
	@GetMapping(value="/findPage")
	public HttpResult findPage(@RequestParam Map<String,Object> params) {
        String page = (String) params.get("page");
        String limit = (String) params.get("limit");
        String name = (String) params.get("name");
        String programID = (String) params.get("programID");
        String selected_program = (String) params.get("selected_program");
        String selected_search = (String) params.get("selected_search");

		PageRequest pageRequest = new PageRequest();
		PageResult result = null;
        if(!"".equals(page)&&!"".equals(limit)) {
            pageRequest.setPage(Integer.parseInt(page));
            pageRequest.setLimit(Integer.parseInt(limit));
        }
		if(!"".equals(name)&&null!=name) {
			ManageEquipment manageEquipment = new ManageEquipment();
			manageEquipment.setName(name);
			result=findPage2(manageEquipment,pageRequest);
		}else if(!"".equals(programID)&&null!=programID) {
			ManageEquipmentExample example = new ManageEquipmentExample();
			ManageEquipmentExample.Criteria citeria = example.createCriteria();
			citeria.andItemEqualTo(programID);
			if(!"".equals(selected_program)&&null!=selected_program&&!"".equals(selected_search)&&null!=selected_search) {
				if("设备类型".equals(selected_program)) {
					citeria.andTypeEqualTo(selected_search);
				}else if("设备位置".equals(selected_program)) {
					citeria.andLocationEqualTo(selected_search);
				}else if("设备状态".equals(selected_program)) {
					if("在线".equals(selected_search)){
						citeria.andStateEqualTo("1");
					}else if("离线".equals(selected_search)){
						citeria.andStateEqualTo("0");
					}
				}
			}
			example.setOrderByClause("Equipment_lastOnlineTime desc");
			result=manageEquipmentBiz.findPage(pageRequest,example);
		}else if(!"".equals(selected_program)&&null!=selected_program&&!"".equals(selected_search)&&null!=selected_search) {
			ManageEquipmentExample example = new ManageEquipmentExample();
			ManageEquipmentExample.Criteria citeria = example.createCriteria();
			if("设备类型".equals(selected_program)) {
				citeria.andTypeEqualTo(selected_search);
			}else if("设备位置".equals(selected_program)) {
				citeria.andLocationEqualTo(selected_search);
			}else if("设备状态".equals(selected_program)) {
				if("在线".equals(selected_search)){
					citeria.andStateEqualTo("1");
				}else if("离线".equals(selected_search)){
					citeria.andStateEqualTo("0");
				}
			}

			example.setOrderByClause("Equipment_lastOnlineTime desc");
			result=manageEquipmentBiz.findPage(pageRequest,example);
		}else {
			ManageEquipment manageEquipment = new ManageEquipment();
			manageEquipment.setName(name);
			result=findPage2(manageEquipment,pageRequest);
		}

		return HttpResult.ok(result);
	}

	private PageResult findPage2(ManageEquipment manageEquipment,PageRequest pageRequest) {
		PageResult result = manageEquipmentBiz.findPage1(pageRequest, manageEquipment);
		return result;
	}

//	@PostMapping(value="/findPage1")
//	@ResponseBody
//	public HttpResult findPageTest(@RequestBody cn.uexpo.lhz.common.oldUtils.PageRequest pageRequest) {
//   	PageResult result=findPage1(pageRequest);
//		return HttpResult.ok(result);
//	}
//
//private PageResult findPage1(@RequestBody cn.uexpo.lhz.common.oldUtils.PageRequest pageRequest) {
//	ManageEquipmentExample example = new ManageEquipmentExample();
//	PageResult result=manageEquipmentBiz.findPage(pageRequest,example);
//	return result;
//}

//	private static File createHallExcelFile(List<?> records) {
//		if (records == null) {
//			records = new ArrayList<>();
//		}
//		Workbook workbook = new XSSFWorkbook();
//		Sheet sheet = workbook.createSheet();
//		Row row0 = sheet.createRow(0);
//		int columnIndex = 0;
//		row0.createCell(columnIndex).setCellValue("No");
//		row0.createCell(++columnIndex).setCellValue("ID");
//		row0.createCell(++columnIndex).setCellValue("展会名");
//		row0.createCell(++columnIndex).setCellValue("是否可用");
//		row0.createCell(++columnIndex).setCellValue("备注");
//		row0.createCell(++columnIndex).setCellValue("创建时间");
//		for (int i = 0; i < records.size(); i++) {
//			Hall hall = (Hall) records.get(i);
//			Row row = sheet.createRow(i + 1);
//			for (int j = 0; j < columnIndex + 1; j++) {
//				row.createCell(j);
//			}
//			columnIndex = 0;
//			row.getCell(columnIndex).setCellValue(i + 1);
//			row.getCell(++columnIndex).setCellValue(hall.getId());
//			row.getCell(++columnIndex).setCellValue(hall.getName());
//			row.getCell(++columnIndex).setCellValue(hall.getUsable());
//			row.getCell(++columnIndex).setCellValue(hall.getRemark());
//			row.getCell(++columnIndex).setCellValue(DateTimeUtils.getDateTime(hall.getCreatetime()));
//		}
//		return PoiUtils.createExcelFile(workbook, "download_hall");
//	}

}
